#include "rostermodel.h"

#include "other/gameStructs.h"
#include "rosterelements.h"
#include "columnheader.h"

#define NAME_COLUMN 0
#define SIZE_COLUMN 1
#define COST_COLUMN header->count()+2

RosterModel::RosterModel(yALB_AbstractTreeItem *rootItem, ColumnHeader *_header, QObject *parent) :
    yALB_AbstractTreeModel(rootItem, parent)
{
    header = _header;

    connect(header, SIGNAL(columnAboutToBeInserted()), this, SLOT(onColumnAboutToBeInserted()));
    connect(header, SIGNAL(columnInserted()), this, SLOT(onColumnInserted()));
    connect(header, SIGNAL(columnsAboutToBeCleared()), this, SLOT(onColumnsAboutToBeCleared()));
    connect(header, SIGNAL(columnsCleared()), this, SLOT(onColumnsCleared()));
}

QVariant RosterModel::data(const QModelIndex &index, int role) const {
    if(!index.isValid())
        return QVariant();

    RosterElement *item = static_cast<RosterElement*>(index.internalPointer());

    if(role == Qt::DisplayRole) {
        return item->text(index.column(), header);
    } else if(role == Qt::UserRole)
        return item->userData(index.column());
    else if (role == Qt::TextAlignmentRole) {
        if(index.column() != 0)
            return Qt::AlignCenter;
        else
            return Qt::AlignLeft + Qt::AlignVCenter;
    }

    return QVariant();
}

QVariant RosterModel::headerData(int section, Qt::Orientation orientation,
                    int role) const {
    if(orientation != Qt::Horizontal)
        return QVariant();
    if(section < 0 || section > header->count()+2)
        return QVariant();

    if(role == Qt::DisplayRole) {
        if(section == NAME_COLUMN)
            return tr("Name");
        else if(section == COST_COLUMN)
            return tr("Cost");
        else if(section == SIZE_COLUMN)
            return tr("#");
        else
            return header->at(section-2).column->getName();
    } else if(role == Qt::UserRole)
        return header->value(section-2).key;
    else if(role == Qt::TextAlignmentRole)
        return Qt::AlignCenter;
    return QVariant();
}

int RosterModel::columnCount(const QModelIndex &parent) const {
    Q_UNUSED(parent)
    return header->count() + 3;
}

void RosterModel::emitDataChanged(RosterElement *element) {
    Q_ASSERT(element);
    emit dataChanged(index(element, 0), index(element, columnCount()));
}

RosterElement* RosterModel::getElementFromIndex(const QModelIndex &index) {
    if(!index.isValid())
        return NULL;
    return static_cast<RosterElement*>(index.internalPointer());
}

void RosterModel::onColumnAboutToBeInserted() {
    int column = header->count() + 2;
    beginInsertColumns(QModelIndex(), column, column);
}

void RosterModel::onColumnInserted() {
    endInsertColumns();
}

void RosterModel::onColumnsAboutToBeCleared() {
    beginRemoveColumns(QModelIndex(), 2, header->count());
}

void RosterModel::onColumnsCleared() {
    endRemoveColumns();
}
